package com.zzq.Service;

import com.zzq.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 幼儿猿大班
 * 2021/7/28
 */
@Component
public class UserService implements UserDetailsService {
    // 静态代码块模拟数据库
    private static HashMap<String, User> userHashMap = new HashMap<>();
    static{
        userHashMap.put("张三",new User("张三","12345"));
        userHashMap.put("李四",new User("李四","99999"));
        userHashMap.put("王五",new User("王五","66666"));
        userHashMap.put("丽丽",new User("丽丽","88888"));
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名获取用户信息
        User user = userHashMap.get(username);
        //System.out.println(username);
        if(user==null){
            return null;
        }

        // 获取密码
        String password=user.getPassword();

        // 授权
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if(user.getUsername().equals("张三")){
            grantedAuthorities.add(new SimpleGrantedAuthority("add"));
        }else if(user.getUsername().equals("李四")){
            grantedAuthorities.add(new SimpleGrantedAuthority("delete"));
        }else if(user.getUsername().equals("王五")){
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_A"));
        }else{
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }

        org.springframework.security.core.userdetails.User user1 = new org.springframework.security.core.userdetails.User(user.getUsername(),"{noop}"+password,grantedAuthorities);
        return user1;
    }
}
